﻿using System;
using System.IO;
using XuanFe.AppLaunch.Common.Security;
using XuanFe.AppLaunch.Common.Xml;

namespace XuanFe.AppLaunch.Config
{
    public class ConfigFactory
    {
        private static string privateKey = "JZTHE2AOX0LCWN1P6GVB8DU4FIY5KS3R";

        private static ConfigFactory instance = new ConfigFactory();

        public static ConfigFactory Instance
        {
            get
            {
                return instance;
            }
        }

        public ConfigFactory()
        {
            this.AppDir = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            this.ConfigDir = Path.Combine(AppDir, "Config");
            this.LogConfigFile = Path.Combine(ConfigDir, "log4net.xml");
            this.ServerConfigFile = Path.Combine(ConfigDir, "server.xml");
        }

        public string AppDir { get; private set; }
        public string ConfigDir { get; private set; }
        public string LogConfigFile { get; private set; }
        public string ServerConfigFile { get; private set; }

        private void CreateConfigDir()
        {
            if (Directory.Exists(ConfigDir)) return;
            Directory.CreateDirectory(ConfigDir);
        }

        /// <summary>
        /// 创建日志配置文件
        /// </summary>
        public void CreateLogConfig()
        {
            CreateConfigDir();
            if (!File.Exists(LogConfigFile))
            {
                LogConfiguration.AppenderItem appenderItem = null;
                LogConfiguration.LoggerItem logger = null;

                LogConfiguration config = new LogConfiguration();

                // 程序级别
                appenderItem = new LogConfiguration.AppenderItem() { Name = "AppAppender", Type = "log4net.Appender.RollingFileAppender" };
                appenderItem.Filters = null;
                appenderItem.File.Value = @"Logs\\";
                appenderItem.AppendToFile.Value = "true";
                appenderItem.LockingModel.Type = @"log4net.Appender.FileAppender+MinimalLock";
                appenderItem.RollingStyle.Value = "Composite";
                appenderItem.DatePattern.Value = @"yyyy-MM-dd\\yyyyMMdd""_App.log""";
                appenderItem.StaticLogFileName.Value = @"false";
                appenderItem.MaxSizeRollBackups.Value = @"-1";
                appenderItem.MaximumFileSize.Value = @"10MB";
                appenderItem.Layout.Type = "log4net.Layout.PatternLayout";
                appenderItem.Layout.ConversionPattern.Value = "%date{yyyy-MM-dd HH:mm:ss,ffff} [%logger] %-5level - %message%newline";
                config.Appenders.Add(appenderItem);

                // 业务级别
                appenderItem = new LogConfiguration.AppenderItem() { Name = "BizAppender", Type = "log4net.Appender.RollingFileAppender" };
                appenderItem.Filters = null;
                appenderItem.File.Value = @"Logs\\";
                appenderItem.AppendToFile.Value = "true";
                appenderItem.LockingModel.Type = @"log4net.Appender.FileAppender+MinimalLock";
                appenderItem.RollingStyle.Value = "Composite";
                appenderItem.DatePattern.Value = @"yyyy-MM-dd\\yyyyMMdd""_Biz.log""";
                appenderItem.StaticLogFileName.Value = @"false";
                appenderItem.MaxSizeRollBackups.Value = @"-1";
                appenderItem.MaximumFileSize.Value = @"10MB";
                appenderItem.Layout.Type = "log4net.Layout.PatternLayout";
                appenderItem.Layout.ConversionPattern.Value = "%date{yyyy-MM-dd HH:mm:ss,ffff} [%logger] %-5level - %message%newline";
                config.Appenders.Add(appenderItem);

                // 数据库级别
                appenderItem = new LogConfiguration.AppenderItem() { Name = "DBAppender", Type = "log4net.Appender.RollingFileAppender" };
                appenderItem.Filters = null;
                appenderItem.File.Value = @"Logs\\";
                appenderItem.AppendToFile.Value = "true";
                appenderItem.LockingModel.Type = @"log4net.Appender.FileAppender+MinimalLock";
                appenderItem.RollingStyle.Value = "Composite";
                appenderItem.DatePattern.Value = @"yyyy-MM-dd\\yyyyMMdd""_DB.log""";
                appenderItem.StaticLogFileName.Value = @"false";
                appenderItem.MaxSizeRollBackups.Value = @"-1";
                appenderItem.MaximumFileSize.Value = @"10MB";
                appenderItem.Layout.Type = "log4net.Layout.PatternLayout";
                appenderItem.Layout.ConversionPattern.Value = "%date{yyyy-MM-dd HH:mm:ss,ffff} [%logger] %-5level - %message%newline";
                config.Appenders.Add(appenderItem);

                logger = new LogConfiguration.LoggerItem() { Name = "AppLogger" };
                logger.Level.Value = "INFO";
                logger.AppenderRefs.Add(new LogConfiguration.AppenderRefItem() { Ref = "AppAppender" });
                config.Loggers.Add(logger);

                logger = new LogConfiguration.LoggerItem() { Name = "BizLogger" };
                logger.Level.Value = "INFO";
                logger.AppenderRefs.Add(new LogConfiguration.AppenderRefItem() { Ref = "BizAppender" });
                config.Loggers.Add(logger);

                logger = new LogConfiguration.LoggerItem() { Name = "DBLogger" };
                logger.Level.Value = "INFO";
                logger.AppenderRefs.Add(new LogConfiguration.AppenderRefItem() { Ref = "DBAppender" });
                config.Loggers.Add(logger);

                XmlConverter.Instance.SerializeFile(LogConfigFile, config);
            }
        }
        public ServerConfiguration LoadServerConfig()
        {
            CreateConfigDir();
            ServerConfiguration config = null;
            if (!File.Exists(ServerConfigFile))
            {
                config = new ServerConfiguration() { Version = "1.0", Server = "127.0.0.1", User = "wsdba", Password = CryptographyHelper.Instance.TripleDESEncryptor(privateKey, "manager"), Database = "wsdb" };
                XmlConverter.Instance.SerializeFile(ServerConfigFile, config);
            }
            else
            {
                config = XmlConverter.Instance.DeserializeFile<ServerConfiguration>(ServerConfigFile);
            }
            return config;
        }
        public void SaveServerConfig(ServerConfiguration config)
        {
            CreateConfigDir();
            XmlConverter.Instance.SerializeFile(ServerConfigFile, config);
        }
    }
}
